<template>
  <div class="container">
    <div class="project-alteration-wrapper" v-if="$route.name === '变更控件'">
      <!-- <div class="title">{{oid}}--{{projectName}}</div> -->
      <div id='btn-content' class="btn-content flex-center">
          <div class="btn-box flex-center">
            <!-- #386bd7 -->
            <a-button type="primary" @click="createAlteration">{{$t('projectChange.createChange')}}</a-button>
             <!-- 任务书处于检入状态才可以编辑 -->
            <!-- <a-button>复制</a-button>-->
            <a-button @click="editAlteration" :disabled="editDisabled">{{$t('projectChange.edit')}}</a-button>
            <!-- <a-button>撤回</a-button> -->
            <a-button @click="delAlteration" :disabled="delDisabled">{{$t('projectChange.delete')}}</a-button>
          </div>
      </div>
      <a-spin :spinning='showTable'>
        <common-table 
          :isRowsSelectVisible="true" 
          :scrollx="false" 
          :columnWidth="50" 
          :columns="columns" 
          :tableData="tableData" 
          :loadVisible="loading"
          @routerPage="routerPage" 
          @selectedRows="selectedRows"
          :data-row-key="'oid'"
        ></common-table>
      </a-spin>
    </div>
    <router-view :key="$route.name" v-if="$route.name !== '变更控件' && !$route.meta.keepAlive"></router-view>
    <keep-alive>
      <router-view :key="$route.name" v-if="$route.name !== '变更控件' && $route.meta.keepAlive"></router-view>
    </keep-alive>
  </div>  
</template>
<script>
 
  import commonTable from "@/components/common/commonTable";
  import { getChangeRequests, deleteChangeRequest, getActionsPermission } from '@/api/projectAlteration'
  import _ from 'lodash'
  let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  export default {
    data() {
      return {
        showTable: false, // 表格loading
        /**表格操作参数 */
        tableData: [],
        hasSelectTableData: [], // 表格已选中数据
        imporTaskBookVisible: false, // 导入任务书弹框
        hasAccess: null, // true 检入状态  false 检出状态
        oid: '',
        projectName: '',
        btnList:[],
        loading:false,
        editDisabled:true,
        delDisabled:true,
      }
    },
    components: { commonTable },
    // watch: {
    //   '$route.path': function(val) {
    //     if (val === '/single/projectPaper') {
    //       this.initData()
    //     }
    //   }
    // },
    computed:{
      columns(){
        return [
          {
            displayName: this.$t('tableList.projectAlteration.number'),
            name: 'number',
            key: 'number',
            fieldType: 'Input',
            dataType: 'String',
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender"
            },
          },
          {
            displayName: this.$t('tableList.projectAlteration.name'),
            name: 'name',
            key: 'name',
            scopedSlots: {
              customRender: "name"
            }
          },
          {
            displayName: this.$t('tableList.projectAlteration.changeCategory'),
            name: 'changeCategory',
            key: 'changeCategory'
          },
          {
            displayName: this.$t('tableList.projectAlteration.planActivity'),
            name: 'planActivity',
            key: 'planActivity'
          },
          {
            displayName: this.$t('tableList.projectAlteration.responsibleUser'),
            name: 'responsibleUser',
            key: 'responsibleUser'
          },
          {
            displayName: this.$t('tableList.projectAlteration.resolvedDate'),
            name: 'resolvedDate',
            key: 'resolvedDate',
            fieldType: 'Date',
            dataType: 'String',
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender"
            },
          },
          // {
          //   displayName: this.$t('tableList.projectAlteration.creator'),
          //   name: 'creator',
          //   key: 'creator'
          // },
          {
            displayName: this.$t('tableList.projectAlteration.createDate'),
            name: 'createDate',
            key: 'createDate',
            fieldType: 'Date',
            dataType: 'String',
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender"
            },
          },
          {
            displayName: this.$t('tableList.projectAlteration.stateDisPlay'),
            name: 'stateDisPlay',
            key: 'stateDisPlay',
            fieldType: 'Select',
            dataType: 'String',
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender"
            },
          }
        ];
      }
    },
    mounted() {
      this.initData()
      // this._getActionsPermission();
    },
    watch:{
      $route(to,from){
        this.editDisabled = true;
        this.delDisabled = true;
        this._getChangeRequests()
        // if(from.name=='创建变更' || from.name=='编辑变更' || from.name=='变更处理'){
        //   this.editDisabled = true;
        //   this.delDisabled = true;
        //   this._getChangeRequests()
        // }
      }
    },
    methods: {
      initData() {
        this.tableData = sessionStorage.getItem('changeItem') ? JSON.parse(sessionStorage.getItem('changeItem')) : []
        return false;
        this.oid = sessionStorage.getItem('oid')
        this.userId = userInfo.loginName
        this._getChangeRequests()
      },
      //获取按钮权限接口
      _getActionsPermission(){
        getActionsPermission({userId: this.userId,oid: `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`, actions: [{"number": "113","id": "create"},{"number": "113","id": "delete"},{"number": "113","id": "editProjectChangeRequest"}]}).then((res)=>{
          this.btnList = res.data.data;
          // console.log(999,res.data.data)
        })
      },
      _getChangeRequests() {
        // this.loading = true;
        getChangeRequests({userId: this.userId, oid: `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`}).then(({data}) => {
          if (data.data && data.data.length) {
            this.tableData = _.orderBy(data.data, ['createDate'], ['desc'])//按照创建时间降序排序 
            let stateDisPlaySelect = []
            data.data.forEach(item => {
              if (!stateDisPlaySelect.includes(item.stateDisPlay)) {
                stateDisPlaySelect.push(item.stateDisPlay)
              }
            })
            this.columns[this.columns.length - 1].fieldValue = stateDisPlaySelect
          }
          this.loading = false;
        })
      },
      createAlteration() {
        if(sessionStorage.getItem('changeAlterationData')){
          let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
          tabArrNew = tabArrNew.filter((rec) => {
            return rec.title !== '编辑变更'
          })
          this.$store.commit('SET_TABS', tabArrNew)
          sessionStorage.setItem('changeAlterationData','{}')
        }
        this.$router.push({
          path:'/single/projectAlteration/createAlteration',
          query: {
            create: true
          }
        })
      },
      editAlteration() {
        let len = this.hasSelectTableData.length
        if (len === 0 || len > 1) {
          this.$message.info('请选择一行数据')
        } else {
          // changeOid要存在sessionStorage中  tabs切换会丢失路由参数
          sessionStorage.setItem('changeOid', this.hasSelectTableData[0].oid)
          // this.$router.push('/single/projectAlteration/editAlteration')
          let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
          tabArrNew = tabArrNew.filter((rec) => {
            return rec.title !== '编辑变更'
          })
          this.$store.commit('SET_TABS', tabArrNew)
          sessionStorage.setItem('changeAlterationData','{}')
          this.$router.push({
            path:'/single/projectAlteration/editAlteration',
          })
          this.hasSelectTableData = [];
        }
      },
      //批量删除
      delAlteration(){
        if(!this.hasSelectTableData.length){
          this.$message.info('请先选择需要删除的内容')
          return false;
        }
        let ids = this.hasSelectTableData.map(item=>{
          return item.oid
        })
        this.$confirm({
          title: '确认删除吗？',
          content: '',
          cancelText: '取消',
          okText: '确认',
          onOk: () => {
            this.showTable = true;
            deleteChangeRequest({userId: this.userId,oids:ids}).then((res)=>{
              if (res && res.data && res.data.success) {
                this.$message.success('删除成功')
                this.delDisabled = true;
                this._getChangeRequests()
              } else {
                this.$message.error(res.data.message)
              }
              this.showTable = false;
            }).catch(()=>{
              this.showTable = false;
            })
          }
        })
      },
      routerPage(val) {
        sessionStorage.setItem('changeOid', val.oid)
        sessionStorage.setItem('changeVal', JSON.stringify(val))
        this.$router.push({
          path: "/single/projectAlteration/detailAlteration",
          query: {
            creator: val.creator == userInfo.realName && (val.stateDisPlay=='处理中' || val.stateDisPlay=='正在审阅'),
            stateDisPlay:val.stateDisPlay
          }
        })
      },
      // 选中数据
      selectedRows(val) {
        this.hasSelectTableData = val
        console.log(this.hasSelectTableData[0])
        if(this.hasSelectTableData.length){
          if(this.hasSelectTableData[0].state=="REWORK"){
            this.editDisabled = false;
          }else{
            this.editDisabled = true;
          }
          if(this.hasSelectTableData[0].state=="CANCELLED"){
            this.delDisabled = false;
          }else{
            this.delDisabled = true;
          }
        }else{
          this.editDisabled = true;
          this.delDisabled = true;
        }
        
        
      },
    }
  }
</script>
<style scoped lang="less">
  @import "./index.less";
  .project-alteration-wrapper .btn-content .btn-box .ant-btn[disabled]:hover{
    color: rgba(0, 0, 0, 0.25);
  }
</style>